<template>
  <div class="product-list">
    <!--顶部切换状态栏-->
    <slot name="topMenu"></slot>
    <div class="my-table" v-loading="loading">
      <el-table :data="productList" @row-click="openRow" :height="$height-224+'px'"
                ref="multipleTable" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="45"></el-table-column>
        <el-table-column label="产品图片" width="80">
          <template slot-scope="scope">
            <img :src="scope.row.defaultPicUrl !== '' ? scope.row.defaultPicUrl : 'img/noTime/pic.png' " alt=""
                 class="product_img">
          </template>
        </el-table-column>
        <el-table-column label="产品名称" prop="productName">
          <template slot-scope="scope">
            <span class="more" :title="scope.row.productEname" @click.stop="toDetail(scope.row.id,scope.row.releaseStatus)">{{scope.row.productEname}}</span>
          </template>
        </el-table-column>
        <el-table-column label="产品编号" prop="productCode"></el-table-column>
        <el-table-column label="产品类型" prop="productTypeName"></el-table-column>
        <el-table-column label="产品分组" prop="typeName"></el-table-column>
        <el-table-column label="离岸价" prop="offshorePrice">
          <template slot-scope="scope">
            {{scope.row.offshoreCurrencyUnitName}}{{scope.row.offshorePrice}}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="160px">
          <template slot-scope="scope">
            {{scope.row.createTime}}
            <p :class="{active:scope.row.releaseStatus==0}">{{scope.row.releaseStatus?'出售中':'仓库中'}}</p>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120px">
          <template slot-scope="scope">
            <a href="javascript:void(0)"  v-show="permission.product_company_fixed">
              <img v-if="filterZero(scope.row.sort)" src="../../../public/img/email/icon/icon-fix.png"
                   @click.stop="fiexdTop(scope.row)"
                   title="置顶" class="delivery-img" alt="置顶">
              <img v-else src="../../../public/img/email/icon/icon-fixed.png"
                   @click.stop="fiexdTop(scope.row)"
                   title="取消置顶" class="delivery-img" alt="取消置顶">
            </a>
            <img  src="../../../public/img/email/icon/icon-email.png" @click.stop="toSend(scope.row.id)"
                 title="发送邮件" class="delivery-img" alt="发送邮件">
            <img v-show="permission.product_company_update" src="../../../public/img/email/icon/icon-edit.png"
                 title="编辑产品" class="delivery-img" alt="编辑产品" @click.stop="toDetail(scope.row.id,scope.row.releaseStatus)">
            <img v-show="permission.product_company_delete"  src="../../../public/img/email/icon/icon-del.png" @click.stop="remove(scope.row.id,scope.row.releaseStatus)"
                 title="删除产品" class="delivery-img" alt="删除产品">
            <el-button v-show="permission.product_company_release" type="primary" size="mini"
                       @click.stop="putOneIntel(scope.row)">
              立即{{scope.row.releaseStatus?'下架':'上架'}}
            </el-button>
          </template>
        </el-table-column>
        <div slot="empty" >
          <div>
            <img src="../../../public/img/empty.png" alt="" style="width: 350px">
          </div>
        </div>
      </el-table>

      <el-pagination align="right" background
                     class="pagination fixed"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="currentPage"
                     :page-size="size"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </div>
    <avue-drawer v-model="dialogVisible" :width="700"
                 style="background-color:#F5F5F5;">
      <ProductReview ref="productReview" :ID="ID" @close="close"></ProductReview>
    </avue-drawer>
    <!--    选择模板-->
    <DialogProductEmail ref="dialogProductEmail"></DialogProductEmail>
  </div>
</template>
<script>
    import {removeProduct, fiexdItem, getProList, putIntel} from '@/api/product'
    import {mapState, mapGetters} from 'vuex'
    import DialogProductEmail from "@/components/product/DialogProductEmail";
    import ProductReview from '@/components/product/ProductReview'

    export default {
        components: {DialogProductEmail, ProductReview},
        props: ['currentNav'],
        data() {
            return {
                dialogVisible: false,
                checkboxarr: [],
                productList: [],
                size: 20,
                total: 0,
                currentPage:1,
                searchVal: '',
                templateList: [],
                formRule: {
                    template: ''
                },
                selection: [],
                isTemp: 0,
                mainHeight: 0,
                ID: 0,
                loading: false
            }
        },
        computed: {
            ...mapState(['common', 'user']),
            ...mapGetters(["permission"]),
        },
        watch: {
            '$route'(to, from) {
                this.dealParam();
            },
            currentNav: {
                immediate: true,
                handler(val) {
                   this.dealParam();
                }
            }
        },
        methods: {
            dealParam(){
                this.currentPage = this.common.commonPage;
                this.size = this.common.commonPageSize;
                this.getData()
            },
            //发布官网
            putOneIntel(row) {
                this.checkboxarr = [row.id];
                var str = !row.releaseStatus ? '上架' : '下架', target = '';
                target += `<li style="padding: 3px 5px;width: 40%;" class="more">产品名称：${row.productEname}</li>`;
                this.sendIntel(str, target, !row.releaseStatus)
            },
            putIntel(state) {
                var str = state ? '上架' : '下架', target = '';
                if(this.selection.length==0){
                    this.$message({
                        type: 'success',
                        message: `请选择要${str}的产品`
                    })
                    return;
                }
                for (let i = 0, len = this.selection.length; i < len; i++) {
                    let item = this.selection[i];
                    target += `<li style="padding: 3px 5px;width: 40%;" class="more">产品名称：${item.productEname}</li>`
                }
                this.sendIntel(str, target, state)
            },
            sendIntel(str, target, state) {
                this.$confirm(' <div style="margin: 20px 10px;">\n' +
                    '<ul style="display: flex;flex-wrap: wrap">' + target + '</ul></div>', str, {
                    dangerouslyUseHTMLString: true,
                    closeOnClickModal: false,
                    closeOnPressEscape: false,
                    confirmButtonText: '确 认',
                    cancelButtonText: '取 消',
                }).then(() => {
                    putIntel(this.checkboxarr, state).then(res => {
                        if (res.data.success) {
                            if (res.data.success) {
                                this.$message({
                                    type: 'success',
                                    message: res.data.msg
                                })
                                this.handleCurrentChange(this.currentPage);//刷新数据
                            }
                        }
                    })
                }).catch((err) => {
                    console.log(err)
                })
            },
            init(param) {
                this.searchVal = param.searchVal;
                this.currentPage = param.currentPage;
                this.checkboxarr = [];
                this.getData();
            },
            getData() {
                if (!this.$route.params.id) return;
                let type = this.currentNav == -1 ? '' : this.currentNav;
                this.loading = true;
                getProList(type, this.$route.params.id, this.currentPage, this.size, this.searchVal).then((res) => {
                    this.loading = false;
                    this.productList = res.data.data.records;
                    this.total = res.data.data.total;
                    if (this.productList.length == 0) {
                        this.mainHeight = 110;
                    } else {
                        this.productList.forEach((value) => {
                            value.defaultPicUrl = value.defaultPicUrl.replace(/&amp;/g, "&")
                        })
                        let oldHeight = 120 * this.productList.length + 32;
                        if (oldHeight > this.$height - 190) {
                            this.mainHeight = this.$height - 190;
                        } else {
                            this.mainHeight = oldHeight;
                        }
                    }
                }).catch(() => this.loading = false)
            },
            chooseTemp(item, index) {
                this.isTemp = index;
                this.formRule.template = item.htmlContent;
            },
            toSend(id) {
                if (this.common.emailList.length == 0) {
                    this.$confirm(' <div style="margin: 20px 10px;">\n' +
                        '        <p style="line-height: 30px;\n' +
                        '        font-size: 14px;">您需要先绑定自己的常用邮箱到我们的平台，才可以使用邮件模块功能哦！</p>\n' +
                        '        <p style="line-height: 30px;\n' +
                        '        font-size: 14px;">点击下方的按钮即可立即去绑定。</p>\n' +
                        '      </div>', '邮箱绑定提醒', {
                        dangerouslyUseHTMLString: true,
                        closeOnClickModal: false,
                        closeOnPressEscape: false,
                        confirmButtonText: '去绑定',
                        cancelButtonText: '取 消',
                    }).then(() => {
                        this.$store.commit('SET_CURRENTSETFRAG', 'eight')
                        this.$router.push('/mail/administration');
                    }).catch(() => {
                    })
                    return;
                }
                this.$refs.dialogProductEmail.init(id);
            },
            handleCurrentChange(page) {
                this.currentPage = page;
                this.checkboxarr = [];
                this.$refs.multipleTable.clearSelection();
                this.getData();
            },
            handleSizeChange(val) {
                this.size = val;
                this.handleCurrentChange(1)
            },
            handleSelectionChange(val) {
                this.checkboxarr = []
                this.selection = val;
                val.map(item => {
                    this.checkboxarr.push(item.id)
                })
            },
            remove(...param) {
                if(param[param.length-1]){
                    this.$alert(' <div style="margin: 20px 10px;">\n' +
                        '        <p style="line-height: 30px;\n' +
                        '        font-size: 14px;">删除产品，需要先对此产品进行下架才能删除！</p>\n' +
                        '      </div>', '系统提示', {
                        dangerouslyUseHTMLString: true,
                        confirmButtonText: '我知道了',
                    }).then(()=>{})
                    return;
                }
                //判断当前
                let arr = [];
                if (param.length ==2) {//单个
                    arr = [param[0]];
                } else {//多个
                    if (this.checkboxarr.length === 0) {
                        this.$message({
                            type: 'success',
                            message: '请先选择要删除的产品'
                        });
                        return;
                    } else {
                        let end = -1;
                        for (let item of this.selection) {
                            if (item.releaseStatus == 1) {//上架中
                                end = item.id
                            }
                        }
                        if (end != -1) {
                            this.$alert('选中商品中存在上架中的商品，请重新选择未上架的商品进行批量删除!', '删除提醒', {
                                confirmButtonText: '我知道了',
                                callback: action => {
                                    return;
                                }
                            }).catch()
                            return;
                        }
                    }
                    arr =this.checkboxarr;
                }
                this.$confirm('此操作将永久删除该产品, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'success',
                }).then(() => {
                    removeProduct(arr).then((res) => {
                        if (res.data.success) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            this.handleCurrentChange(1);//刷新数据
                        }
                    })
                })
            },
            toDetail(id,state) {
                if(!this.permission.product_company_update)return;//只针对产品名称
                if(state){
                    this.$alert(' <div style="margin: 20px 10px;">\n' +
                        '        <p style="line-height: 30px;\n' +
                        '        font-size: 14px;">编辑产品，需要先对此产品进行下架才能编辑！</p>\n' +
                        '      </div>', '系统提示', {
                        dangerouslyUseHTMLString: true,
                        confirmButtonText: '我知道了',
                    }).then(()=>{})
                    return;
                }
                this.$store.commit('SET_COMMONPAGE', {page: this.currentPage, pageSize: this.size});
                this.$router.push({
                    path: `/product/edit/${id}`,
                    query:{
                        type:0
                    }
                })
            },
            openRow(row) {
                this.dialogVisible = true;
                this.ID = row.id;
            },
            close() {
                this.dialogVisible = false;
            },
            fiexdTop(item) {
                let state = this.filterZero(item.sort);
                this.$confirm(`确认${state ? '' : '取消'}置顶该产品?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'success',
                }).then(() => {
                    fiexdItem(item.id, state).then((res) => {
                        if (res.data.success) {
                            this.$message({
                                type: 'success',
                                message: res.data.msg
                            })
                            this.handleCurrentChange(this.currentPage);//刷新数据
                        }
                    })
                })
            },
            filterZero(sort) {
                if (sort == 0 || sort == '') {
                    return true
                } else {
                    return false;
                }
            }
        }
    }
</script>

<style lang="scss" scoped>
  $blue: #2A97F9;
  .product-list {
    margin-top: 20px;


    .my-table {

      table {
        width: 100%;
        font-size: 13px;
        text-align: left;

        thead {
          tr {
            line-height: 30px;
            background-color: #EAF0F6;

          }
        }

        thead, tbody tr {
          display: table;
          width: 100%;
          table-layout: fixed;
        }

        tbody {
          color: #232323;
          overflow-y: auto;

          tr {
            border-bottom: 1px solid #F3F3F3;

            td {
              padding: 15px 0;

              span {
                color: $blue;
                padding-right: 10px;
              }

              p {
                color: #139890;
              }

              p.active {
                color: #DA752E;
              }

              .el-button {
                height: 24px;
                border-radius: 10px;
                display: block;
                margin-top: 5px;
                padding: 0 20px;
                font-size: 12px;
                border: none;
              }
            }

          }
        }

        .product_img {
          width: 50px;
          height: 50px;
          vertical-align: middle;
        }

        .delivery-img {
          width: 16px;
          vertical-align: middle;
          margin-right: 8px;
        }


      }

      .detail {
        overflow-y: auto;
      }
    }
  }

</style>
